package net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    //代码会涉及到多个Socket对象，使用不同的名字来区分
    private ServerSocket listenSocket = null;

    public TcpEchoServer(int port) throws IOException {
        listenSocket = new ServerSocket(port);
    }

    public void Start() throws IOException {
        System.out.println("服务器启动!");
        //线程池的创建(目前我还没学过...)
        ExecutorService service = Executors.newCachedThreadPool();
        while(true){
            //1.调用accept来接受客户端的连接
            Socket clientSocket = listenSocket.accept();
            //2.再处理这个连接，这里应该要使用多线程，每个客户端连上来都分配一个新的线程处理
            //此处使用多线程确实可以解决问题，但是会导致频繁的创建销毁线程！(故使用线程池！)
//            Thread t = new Thread(()->{
//                try{
//                    processConnection(clientSocket);
//                } catch (Exception e) {
//                    e.getStackTrace()
//                }
//            });
//            t.start();

            service.submit(new Runnable() {
                @Override
                public void run() {
                    try{
                        processConnection(clientSocket);
                    } catch (Exception e) {
                        e.getStackTrace();
                    }
                }
            });
        }
    }

    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%d] 客户端上线!\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
        //接下来就是处理客户端的请求
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            while(true){
                //1.读取请求并解析
                Scanner scanner = new Scanner(inputStream);
                if(!scanner.hasNext()){
                    System.out.printf("[%s:%d] 客户端下线!\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
                    break;
                }
                String request = scanner.next();
                //2.根据请求计算响应(回显)
                String response = process(request);
                //3.把响应写回给客户端
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(response);
                //刷新缓冲区确保数据确实通过网卡发送出去了
                printWriter.flush();

                System.out.printf("[%s:%d] request: %s; response: %s\n",clientSocket.getInetAddress().toString(),
                        clientSocket.getPort(),request,response);
            }
        } catch (IOException e) {
            e.getStackTrace();
        }finally {
            clientSocket.close();
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.Start();
    }

}
